package com.jinke.api.modules.app.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.jinke.api.modules.base.constant.RedisKeyConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @projectName:
 * @title: NoModelDataListener
 * @description:
 * @see:
 * @author: hhp
 * @version: 1.0.0
 * @createTime: 2024/8/1 13:56
 */
@Slf4j
@Component
@Scope("prototype")
@RequiredArgsConstructor
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {

    private final RedisTemplate redisTemplate;
    private List<String> dataList = Lists.newArrayList();

    private String redisKey;

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        data.forEach((key, value) -> {
            if (isNumeric(value)) {
                dataList.add(value);
            }
        });
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        redisTemplate.opsForList();
        //redisTemplate.opsForList().trim();
        log.info("redisKey:{}, size:{}, dataList:{}", redisKey, dataList.size(), dataList);
        // 放入redis
        //String hiZipCodeKey = RedisKeyConstants.ZIP_CODE_PREFIX + RedisKeyConstants.HI_ZIP_CODE_PREFIX;
        Boolean b = redisTemplate.hasKey(redisKey);
        if (b) {
            // 先清空旧数据
            redisTemplate.delete(redisKey);
        }
        redisTemplate.opsForList().leftPushAll(redisKey, dataList);
    }

    public void setRedisKey(String redisKey) {
        this.redisKey = redisKey;
    }

    public void setDataList(List<String> dataList) {
        this.dataList = dataList;
    }

    private static boolean isNumeric(String str) {
        if (StrUtil.isNotBlank(str)) {
            String regex = "\\d+";
            return str.matches(regex);
        }
        return false;
    }
}
